//
//  StatusPictureView.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/15.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
private let pictureCellMargin: CGFloat = 5
private let pictureCellID = "pictureCellID"
class StatusPictureView: UICollectionView {
    
    var imageURLs: [NSURL]? {
        didSet{
//            print(imageURLs)
            reloadData()
            let viewSize = calcuPictureSize()
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
            testLabel.text = "\(imageURLs?.count ?? 0)"
        }
    }
    
    //计算视图配图大小
    private func calcuPictureSize() -> CGSize{
        //获取配图最大宽度
        let column:CGFloat = 3
        
        let maxWidth = kScreenSize.width - 2 * statusCellMargin
        
        //单个图片宽度
        let itemWidth = (maxWidth - 2 * pictureCellMargin) / column

        //设置流水布局
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
//        layout.minimumLineSpacing = pictureCellMargin
//        layout.minimumInteritemSpacing = pictureCellMargin
        let imageCount = imageURLs?.count ?? 0
        if imageCount == 0 {
            return CGSizeZero
        }
        //单张图片
        if imageCount == 1 {
//            let imageSize = CGSize(width: 120, height: 180)
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            let imageSize = image.size
            layout.itemSize = imageSize
            return imageSize
        }
        
        //两张图片
        if imageCount == 2 {
            let w = itemWidth * 2 + pictureCellMargin
            return CGSize(width: w, height: itemWidth)
        }
        
        //四张图片
        if imageCount == 4 {
            let w = itemWidth * 2 + pictureCellMargin
            return CGSize(width: w, height: w)
        }
        
        //多张图片
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = maxWidth
        let h = row * itemWidth + (row - 1) * pictureCellMargin
        return CGSize(width: w, height: h)
    }

    init() {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: pictureCellID)
        dataSource = self
        backgroundColor = UIColor.randomColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
//        backgroundColor = UIColor.randomColor()
        addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    private lazy var testLabel: UILabel = {
        let l = UILabel()
        l.font = UIFont.systemFontOfSize(30)
        l.textColor = UIColor.yellowColor()
        l.sizeToFit()
        return l
    }()
}

extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! StatusPictureCell
        cell.url = imageURLs![indexPath.row]
        return cell
    }
    
}


class StatusPictureCell: UICollectionViewCell {
    
//    private lazy var pictureView: UIImageView = UIImageView()
    private lazy var pictureView: UIImageView = {
        let IMGV = UIImageView()
        //设置图片显示样式
        IMGV.contentMode = UIViewContentMode.ScaleAspectFill
        //对图片进行剪裁，手写代码的时候必须手动添加剪裁
        IMGV.clipsToBounds = true
        return IMGV
    }()
    
    var url: NSURL? {
        didSet{
            pictureView.sd_setImageWithURL(url, placeholderImage: nil)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        contentView.addSubview(pictureView)
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
}


